package model

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

// 对应数据库
type User struct {
	UserID    int    `gorm:"column:userID;type:int(10) unsigned not null AUTO_INCREMENT;primary_key" json:"UserID,string"`
	UserName  string `gorm:"column:userName"`
	UserEmail string `gorm:"column:userEmail"`
	UserPhone string `gorm:"column:userPhone"`
}

func (table User) TableName() string {
	return "user"
}

func GetUserList() {
	data := make([]*User, 0)
	err := Db.Find(&data).Error
	if err != nil {
		fmt.Println(err)
	}
	for _, v := range data {
		fmt.Printf("%v", v)
	}
}

// https://juejin.cn/post/7192053234620432441#heading-13
func GetUser(c *gin.Context) {
	id := c.Query("id")
	var user User
	Db.First(&user, id)
	byte_arr, _ := json.Marshal(user)
	c.Writer.Write(byte_arr)
}

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	var users []User
	Db.Limit(pageSize).Offset((page - 1) * pageSize).Find(&users)
	byte_arr, _ := json.Marshal(users)
	c.Writer.Write(byte_arr)
}

func ModifyUser(c *gin.Context) {
	userobj := User{}
	err := c.ShouldBind(&userobj)
	if err != nil {
		fmt.Println(err)
	}
	Db.Updates(&userobj)
	c.Writer.Write([]byte("{\"code\":\"success\"}"))
}

func AddUser(c *gin.Context) {
	userobj := User{}

	err := c.ShouldBind(&userobj)
	if err != nil {
		fmt.Println(err)
	}
	Db.Create(&userobj)
	c.Writer.Write([]byte("{\"code\":\"success\"}"))
}

func DeleteUser(c *gin.Context) {
	userID, _ := strconv.Atoi(c.Query("id"))
	user := &User{
		userID,
		"",
		"",
		"",
	}
	Db.Delete(&user)
	c.Writer.Write([]byte("{\"code\":\"success\"}"))
}

func UserCount(c *gin.Context) {
	var total int64
	var users []User
	Db.Find(&users).Count(&total)
	c.Writer.Write([]byte(strconv.Itoa(int(total))))
}
